/**
 * 用户喜欢（喜欢/点赞/收藏）路由
 */

var router = require('express').Router();
var assertAlljs = require('../bin/util/assert-alljs');
var dbentityTool = require('../bin/dbentity');
var ObjectID = require('mongodb').ObjectID;
var fondTool = require('../bin/fond');
var userTool = require('../bin/user');
var articleMarkTool = require('../bin/articleMark');

router.post('/fond', async function(req, res) {
    let assert = assertAlljs(req, res, 'json');

    // 检查是否登录
    if (await assert(userTool.check(req.session.user)))
        return;

    if (await assert(typeof(req.body.article_id) !== 'string' || typeof(req.body.path) !== 'string', '缺少请求参数'))
        return;

    // 尝试删除对应路径的点赞
    let {fond, filter, error} = fondTool.fromBody(req.body, req.session.user);
    if (await assert(error))
        return;
    let result = await dbentityTool.deleteMany('fond', filter);
    if (await assert(result instanceof Error))
        return;

    // 如果没有删除到，即不存在，则添加。即切换"点赞/取消点赞"
    let plus = (result.deletedCount < 1) ? 1 : -1;
    if (plus === 1){
        fondTool.newDetails(fond, req.session.user);
        await dbentityTool.upsert('fond', fond);
    }

    // 更新点赞数
    await articleMarkTool.handleFond(fond.article_id, fond.path, plus);

    res.json({success:true, result:plus });
});

module.exports = router;